var prefix = jsctx + "/hlhtTenantOpenList";

var stationHlhtTenantOpen = (function () {
    function init() {
        load();
        console.info($("#hlhtOpenType").val());

        if ($("#hlhtOpenType").val() != 2) {
            $('#exampleTable').bootstrapTable('hideColumn', 'tenantOperatorName');
            $('#exampleTable').bootstrapTable('hideColumn', 'tenantOperatorLoginName');
        }
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function load() {
        // $(function () {
        //     // console.log($("#hlhtOperatoList").val());
        //
        // })
        //   console.log($("#hlhtOperatoList option:selected").val());
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageHlhtTenantOpenStation",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    cache: false,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            tenantOpenId: $("#tenantOpenId").val(),
                            // tenantCode: $("#tenantCode").val().trim(),
                            // hlhtTenantCode: $("#hlhtTenantCode").val().trim(),
                            // hlhtOperatorId: $("#hlhtOperatorId").val().trim(),
                            // hlhtType: $("#hlhtType").val().trim(),
                            hlhtTenantCode2: $("#hlhtTenantList option:selected").val(),
                            hlhtOperatorId: $("#hlhtOperatoList option:selected").val(),
                            stationName: $("#stationName").val(),
                            cityId: $("#cityId").val(),
                            address: $("#address").val(),
                            isOpen: $("#isOpen").val(),
                            operateStatus: $("#operateStatus").val(),
                            hlhtOpenforType: $("#hlhtOpenforType").val()
                        }
                    },
                    columns: [
                        {
                            checkbox: true, field: '', width: '50', align: 'left',
                        },
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'stationTenant', title: '运营商', align: 'left', width: '100'},
                        {field: 'tenantOperatorName', title: '申报分销商', align: 'left', width: '100'},
                        {field: 'tenantOperatorLoginName', title: '账号', align: 'left', width: '100'},
                        {field: 'stationName', title: '充电站', align: 'left', width: '100'},
                        {field: 'cityName', title: '地区', align: 'center', width: '100'},
                        {
                            field: '', title: '充电桩', align: 'center', width: '100',
                            formatter: function (value, row, index) {

                                return '<span>直' + row.directCurrent + '交' + row.alternatingCurrent + '</span>'

                            }
                        },
                        {
                            field: 'operateStatus', title: '站点状态', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '1') {
                                    return '<span>正常使用</span>'
                                } else {
                                    return '<span >异常</span>'
                                }
                            }
                        },
                        {
                            field: 'hlhtElectStationId', title: '是否开放', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == null || value == '') {
                                    return '<span>否</span>'
                                } else {
                                    return '<span >是</span>'
                                }
                            }
                        },
                        {
                            field: 'hlhtOperatorShortnames', title: '是否允许开放给外部第三方', width: '110', align: 'center',
                            formatter: function (value, row, index) {
                                if (value.length > 0) {
                                    return '是'
                                } else {
                                    return '否'
                                }
                            }
                        },

                        {
                            title: '操作',
                            field: 'roleId',
                            width: '200', align: 'center',
                            formatter: function (value, row, index) {
                                var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="stationHlhtTenantOpen.editStationHlhtTenantOpen(\''
                                    + row.priceId
                                    + '\')">编辑</a> ';
                                var b = '<a class="btn btn-primary btn-sm ' + has_edit + '"href="#" onclick="stationHlhtTenantOpen.openPrice('
                                    + row.elecStationId + ",\'" + $("#tenantOpenId").val()
                                    + '\')">推送价格设置</a> ';


                                var c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#"  onclick="stationHlhtTenantOpen.saveOrUpdateHlhtTenantOpenStation('
                                    + row.elecStationId + "," + row.openStationId + "," + $("#tenantOpenId").val()
                                    + ')">开放</a> ';
                                var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#"  onclick="stationHlhtTenantOpen.deleteHlhtTenantOpenStation('
                                    + row.openStationId
                                    + ')">关闭</a> ';
                                var e = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#"  onclick="stationHlhtTenantOpen.detailStation('
                                    + row.elecStationId
                                    + ')">查看详情</a> ';
                                var g = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#"  onclick="stationHlhtTenantOpen.hlhtTenantOpenPile('
                                    + row.elecStationId + "," + $("#tenantOpenId").val()
                                    + ')">桩列表</a> ';
                                if (row.openStationId == null) {
                                    return e + g;
                                } else {
                                    return e + g;
                                }

                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addStationHlhtTenantOpen(elecStationId) {
        location.href = prefix + "/addStationHlhtTenantOpen/" + elecStationId;
    }

    function editStationHlhtTenantOpen(priceId) {
        location.href = prefix + "/editStationHlhtTenantOpen/" + priceId;
    }

    function stationHlhtTenantOpenListPage(stationHlhtTenantOpenId) {
        location.href = prefix + "/stationHlhtTenantOpenListPage/" + stationHlhtTenantOpenId;
    }

    function detailStation(OpenStationId) {
        location.href = prefix + "/detailStation/" + OpenStationId;

    }

    function deleteHlhtTenantOpenStation(OpenStationId) {
        $.ajax({
            url: prefix + "/deleteHlhtTenantOpenStation",
            type: "post",
            data: {
                'OpenStationId': OpenStationId
            },
            success: function (data) {
                if (data.status == 200) {
                    layer.msg(data.message);
                    reLoad();
                } else {
                    layer.msg(data.message);
                }
            }
        });
    }

    function saveOrUpdateHlhtTenantOpenStation(elecStationId, OpenStationId, tenantOpenId) {
        $.ajax({
            url: prefix + "/saveOrUpdateHlhtTenantOpenStation",
            type: "post",
            data: {
                'elecStationId': elecStationId,
                'OpenStationId': OpenStationId,
                'tenantOpenId': tenantOpenId
            },
            success: function (data) {
                if (data.status == 200) {
                    layer.msg(data.message);
                    reLoad();
                } else {
                    layer.msg(data.message);
                }
            }
        });

    }


    function deleteStationHlhtTenantOpen(priceId) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteStationHlhtTenantOpen",
                type: "post",
                data: {
                    'priceId': priceId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function goBack() {
        window.history.back();
    }


    function batchOpenRows() {
        var rows = $("#exampleTable").bootstrapTable('getSelections');//
        if (rows.length == 0) {
            alert("请先选择要开放的记录!");
            return;
        } else {

            var list = new Array();
            $(rows).each(function () {
                if (this.openStationId == null) {
                    list.push(this.elecStationId);
                }

            });
            batchOpen(list);
        }
    }

    function batchOpen(elecStationIdList) {
        layer.confirm('确定批量开放？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/saveBatchHlhtTenantOpenStation",
                type: "post",
                data: {
                    elecStationIdList: elecStationIdList,
                    tenantOpenId: $("#tenantOpenId").val()
                },
                traditional: true,
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg(data.message);
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    var clickFlag ;

    function batchHandleRows(a) {
        var rows = $("#exampleTable").bootstrapTable('getSelections');//
        if (rows.length == 0) {
            alert("请先选择要设置的记录!");
            return;
        } else {
            var openStationIdList = new Array();
            $(rows).each(function () {
                if (this.openStationId != null) {
                    openStationIdList.push(this.openStationId);
                }
            });
            var elecStationIdList = [];
            $(rows).each(function () {
                if (this.elecStationId != null) {
                    elecStationIdList.push(this.elecStationId);
                }

            });
            if (openStationIdList.length == 0) {
                openStationIdList = null
            }
            if (elecStationIdList.length == 0) {
                elecStationIdList = null
            }


            // console.log(a);
            //外部反向
            if (a == "") {
                layer.open({
                    type: 1,
                    title: '开放站点设置',
                    closeBtn: false,
                    shade: 0.4,
                    shift: 7,
                    area: ["400px", "230px"],
                    shadeClose: true,
                    content: $("#open-main"),
                    btn: ['确定', '取消'],
                    yes: function (index) {//layer.msg('yes');    //点击确定回调
                        var openStatus = $("input[name='openStatus']:checked").val();
                        // alert(openStatus);
                        // var hlhtOpenforType = $("input[name='hlhtOpenforType']:checked").val();
                        var tenantOpenId = $("#tenantOpenId").val();

                        layer.close(index);
                        $.ajax({
                            url: prefix + "/updateOrSaveHlhtTenantOpenStation",
                            type: "post",
                            data: {
                                openStationIdList: openStationIdList,
                                elecStationIdList: elecStationIdList,
                                tenantOpenId: $("#tenantOpenId").val(),
                                openStatus: openStatus,
                                hlhtOpenforType: '1',
                                hlhtOperatorIds: ''

                            },
                            traditional: true,
                            success: function (data) {
                                layer.close(index);
                                if (data.status == 200) {
                                    reLoad();
                                    layer.msg(data.message);
                                } else {
                                    layer.msg(data.message);
                                }
                            }
                        });
                    },
                });
            }
            //内部反向
            else {
                // $('input:radio[name="hlhtOpenforType"]').change(function () {
                //     if ($("#swar").is(":checked")) {
                //         alert('1');
                //         // $("#myAdmin").show();
                //         $('#swav').css('dispaly','none');
                //         $('#swaw').css('dispaly','none');
                //     }
                //     if ($("#raws").is(":checked")) {
                //         // $("#myAdmin").hide();
                //         // $("#netPoint").text('');
                //         $('#swav').css('dispaly','block');
                //         $('#swaw').css('dispaly','block');
                //     }
                // });
                layer.open({
                    type: 1,
                    title: '开放站点设置',
                    closeBtn: false,
                    shade: 0.4,
                    shift: 7,
                    area: ["400px", "230px"],
                    shadeClose: true,
                    content: $("#open-main-ex"),
                    btn: ['确定', '取消'],
                    yes: function (index) {//layer.msg('yes');    //点击确定回调
                        var openStatus = $("input[name='openStatusex']:checked").val();
                        if (openStatus == '1') {
                            var hlhtOpenforType = '1';
                            var hlhtOperatorIds = '';
                        } else {
                            var hlhtOpenforType = $("input[name='hlhtOpenforType']:checked").val();
                            var arr_box = [];

                            $(".milk input[type='checkbox']").each(function () {
                                arr_box.push($(this).val());

                            });
                            var hlhtOperatorIds;
                            if (arr_box.length == 0) {
                                hlhtOperatorIds = '';
                            } else {
                                hlhtOperatorIds = arr_box;
                            }
                        }
                        // alert(openStatus);
                        // var hlhtOpenforType = $("input[name='hlhtOpenforType']:checked").val();
                        // var tenantOpenId = $("#tenantOpenId").val();


                        // layer.close(index);
                        $.ajax({
                            url: prefix + "/updateOrSaveHlhtTenantOpenStation",
                            type: "post",
                            data: {
                                openStationIdList: openStationIdList,
                                elecStationIdList: elecStationIdList,
                                tenantOpenId: $("#tenantOpenId").val(),
                                openStatus: openStatus,
                                hlhtOpenforType: hlhtOpenforType,
                                hlhtOperatorIds: hlhtOperatorIds

                            },
                            traditional: true,
                            success: function (data) {
                                console.log(data);
                                layer.close(index);
                                if (data.status == 200) {
                                    reLoad();
                                    layer.msg(data.message);
                                } else {
                                    layer.msg(data.message);
                                }
                            }
                        });
                    },
                });
            }

            //batchDelete(openStationIdList);
        }
    }

    function updateHlhtTenantOpenPriceForBatchOpenStation() {
        var rows = $("#exampleTable").bootstrapTable('getSelections');
        if (rows.length == 0) {
            alert("请先选择要开放的记录!");
            return;
        } else {
            var elecStationIdList = new Array();
            $(rows).each(function () {
                elecStationIdList.push(this.elecStationId);
            });

            layer.open({
                type: 1,
                title: '互联价格批量调整',
                closeBtn: false,
                shade: 0.4,
                shift: 7,
                shadeClose: true,
                content: `<div style='width:350px;padding:10px;text-align: left'>
                        <div >
                        <span style="font-size: 16px">调整服务费:</span>
                        <input type="text" id="adjustValue" maxlength="4" onkeyup="this.value>=0?this.value=this.value:this.value=''" style="width: 100px;height: 30px;margin-left: 10px;text-align: center"  value="1"><span style="margin-left: 5px">元/度</span>
                        </div>
                         <span>说明：针对站点原始电价的服务费进行增加或是减少调整。如某站的原始服务费为0.6元/度，调整服务费为0.1，则调整后的互联服务费是0.7元/度。以该互联服务费+原基本电价作为推送价格给到互联方。</span>
                       </div>`,
                btn: ['确定', '取消'],
                yes: function (index) {//layer.msg('yes');    //点击确定回调
                    if (!$("#adjustValue").val()) {
                        layer.msg("请输入服务费");
                        return;
                    }
                    layer.close(index);
                    $.ajax({
                        url: prefix + "/updateHlhtTenantOpenPriceForBatchOpenStation",
                        type: "post",
                        data: {
                            elecStationIdList: elecStationIdList,
                            tenantOpenId: $("#tenantOpenId").val(),
                            adjustValue: $("#adjustValue").val()

                        },
                        traditional: true,
                        success: function (data) {
                            layer.close(index);
                            if (data.status == 200) {
                                layer.msg(data.message);
                            } else {
                                layer.msg(data.message);
                            }
                        }
                    });
                },
            });


        }

    }

    function batchDelete(openStationIdList) {
        layer.confirm('确定批量关闭？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteBatchHlhtTenantOpenStation",
                type: "post",
                data: {
                    openStationIdList: openStationIdList,

                },
                traditional: true,
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg(data.message);
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        });
    }

    function openPrice(elecStationId, tenantOpenId) {
        location.href = prefix + "/openPrice?elecStationId=" + elecStationId + "&tenantOpenId=" + tenantOpenId;
    }

    function hlhtTenantOpenPile(elecStationId, tenantOpenId) {
        location.href = prefix + "/hlhtTenantOpenPile?tenantOpenId=" + tenantOpenId + "&elecStationId=" + elecStationId;
    }

    function exportHlhtTenantOpenStation() {

        $.fileDownload(prefix + "/exportHlhtTenantOpenStation", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                tenantOpenId: $("#tenantOpenId").val().trim(),
                stationName: $("#stationName").val(),
                cityId: $("#cityId").val(),
                address: $("#address").val(),
                isOpen: $("#isOpen").val(),
                operateStatus: $("#operateStatus").val(),
                hlhtTenantCode2: $("#hlhtTenantList option:selected").val(),
                hlhtOperatorId: $("#hlhtOperatoList option:selected").val(),
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        });
    }


    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };


    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        saveOrUpdateHlhtTenantOpenStation: saveOrUpdateHlhtTenantOpenStation,
        batchHandleRows: batchHandleRows,
        deleteHlhtTenantOpenStation: deleteHlhtTenantOpenStation,
        detailStation: detailStation,
        exportHlhtTenantOpenStation: exportHlhtTenantOpenStation,
        openPrice: openPrice,
        hlhtTenantOpenPile: hlhtTenantOpenPile
    };
})();

var addStationHlhtTenantOpen = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    function save() {
        $("#roleIds").val(getCheckedRoles());
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveOrUpdateStationHlhtTenantOpen",
            data: $('#addStationHlhtTenantOpen').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    stationHlhtTenantOpen.goBack();
                } else {
                    parent.layer.alert(data.message)
                }

            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#addStationHlhtTenantOpen").validate({
            rules: {
                elecPrice: {
                    required: true,
                    number: true,
                    min: 0,
                },
                servicePrice: {
                    required: true,
                    number: true,
                    min: 0,
                },
                beginTime: {
                    required: true
                },
                endTime: {
                    required: true
                }
            },
            messages: {
                elecPrice: {
                    required: icon + "请输入基本电费单价",
                    number: icon + "基本电费价格式不正确，请输入正确格式",
                    min: icon + "基本电费价不能为负数"
                },
                servicePrice: {
                    required: icon + "请输入基本电费单价",
                    number: icon + "基本电费价格式不正确，请输入正确格式",
                    min: icon + "基本电费价不能为负数"
                },
                beginTime: {
                    required: icon + "请选择开始时间"
                },
                endTime: {
                    required: icon + "请选择结束时间"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();




